import $parse from 'spore-kit-location/parse'

// 通过万象服务，获取图片变更格式，转换后的地址
// 万象服务文档
// https://cloud.tencent.com/document/product/460/36540#.E5.8F.82.E6.95.B0.E8.AF.B4.E6.98.8E
// 解决服务使用图片过大的问题

/**
 * @name getImgUrl
 * @param <object> options
 * @param <string> options.url 原图片地址
 * @param <string> [options.type='jpg'] 图片格式，可选: ['jpg','png','gif','webp']
 * @param <number> options.size 图片宽度
 * @param <string> options.extra 额外服务参数
 * @param <boolean> [options.https=true] 使用 https 地址
 * @return <string> 转换后的图片地址
 * @example
 * getImgUrl({
 * 	url: 'http://jietufengmian-1259242701.image.myqcloud.com/20191014/1938112659358/8b6b3b32948e217b4ab0f681b453838e.png'
 * })
 * // https://cover.yangshipin.cn/20191014/1938112659358/8b6b3b32948e217b4ab0f681b453838e.png?imageMogr2/format/jpg/thumbnail/750x
 * getImgUrl({
 * 	url: 'http://mpuser.ysp.cctv.cn/media-icon/180943480860778251567324079236.png?imageMogr2/crop/192x192',
 * 	size: 200
 * })
 * // https://mpuser.ysp.cctv.cn/media-icon/180943480860778251567324079236.png?imageMogr2/crop/192x192|imageMogr2/format/jpg/thumbnail/200x
 */

const cosMap = {
	'livescreenshot-1259242701.file.myqcloud.com': 'livescreecshot.ysp.cctv.cn',
	'h5-staticapi-1259242701.cos.ap-beijing.myqcloud.com': 'sapi.yangshipin.cn',
	'h5-static-1259242701.cos.ap-beijing.myqcloud.com': 's.yangshipin.cn',
	'jietufengmian-1259242701.image.myqcloud.com': 'cover.yangshipin.cn',
	'app-userimg-1259242701.image.myqcloud.com': 'pic.yangshipin.cn',
	'app-userimg-1259242701.cos.ap-beijing.myqcloud.com': 'pic.yangshipin.cn'
}

function getImgUrl (options) {
	let conf = {
		url: '',
		type: 'jpg',
		size: 750,
		https: true,
		extra: '',
		// 启用万象优图服务
		imageMogr: true,
		...options
	}

	if (!conf.url) {
		return conf.url
	}

	if (typeof conf.url !== 'string') {
		return conf.url
	}

	try {
		let loc = $parse(conf.url)
		if (cosMap[loc.host]) {
			loc.host = cosMap[loc.host]
		}

		if (conf.https) {
			loc.scheme = 'https'
		}

		if (conf.imageMogr) {
			let actionType = ''
			if (conf.type) {
				actionType = `/format/${conf.type}`
			}

			let actionSize = ''
			if (conf.size) {
				actionSize = `/thumbnail/${conf.size}x`
			}

			let strMogr = `imageMogr2${actionType}${actionSize}${conf.extra}`

			// 替换之前的万象优图配置
			if (loc.query && loc.query.indexOf('imageMogr') >= 0) {
				loc.query = loc.query.replace(/imageMogr([^&]+)/i, `imageMogr$1|${strMogr}`)
			} else {
				let connector = loc.query ? '&' : ''
				loc.query += connector + strMogr
			}
		}

		let url = `${loc.scheme}://${loc.host}/${loc.path}?${loc.query}`
		return url
	} catch (err) {
		return conf.url
	}
}

export default getImgUrl
